package com.douwong.student.popuwindow;

import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.douwong.student.R;
import com.douwong.student.model.AppInfos;
import com.douwong.student.utils.FileUtils;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

/**
 * apk下载
 * @author Administrator
 *
 */
public class APKLoadPpopu extends PopupWindow {

	private Context context;
	private View view=null,localView=null;
	private TextView pro_text;
	private ProgressBar update_pro;
	private static final int UPDATE_PRO = 2;
	private static final int UPDATE_COMPLETE = 3;
	private static final int LOAD_ERROR = 4;
	private static final int SHOWDOWNLOAD_DIALOG=5;
	private long length;
	private AppInfos appInfos;
	public APKLoadPpopu(Context context, AppInfos appInfos, View localView){
		this.context=context;
		this.appInfos=appInfos;
		this.localView=localView;
		LayoutInflater inflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		view=inflater.from(context).inflate(R.layout.apk_load, null);
		pro_text=(TextView) view.findViewById(R.id.pro_text);
		update_pro=(ProgressBar) view.findViewById(R.id.update_pro);
		this.setContentView(view);
		this.setWidth(LayoutParams.MATCH_PARENT);
		this.setHeight(LayoutParams.MATCH_PARENT);
		this.setFocusable(false);
		ColorDrawable dw = new ColorDrawable(0x4c000000);
		this.setBackgroundDrawable(dw);
	}
	//更新进度
		public void  setProgress(int progress){
			pro_text.setText(progress+"%");
			update_pro.setProgress(progress);
		}
		private Handler handler = new Handler() {
			public void handleMessage(Message msg) {
				 if (msg.what == UPDATE_PRO) {// 更新下载进度
					setProgress(msg.arg1 * 100 / (int) length);
				} else if (msg.what == UPDATE_COMPLETE) {// 下载完成
					 dismiss();
					 //Log.w("APKLoadPpopu","start install in fordel  :"+FileUtils.APK_DIR);
					 File file=new File(FileUtils.APK_DIR,appInfos.appName);
					 if(file.exists()){
						 long fileSize=file.length();
						 if(length==fileSize){
							 FileUtils.installApk(context,appInfos.appName);
						 }else {
							 Toast.makeText(context, "下载失败，文件损坏！", Toast.LENGTH_LONG).show();
							 file.delete();
						 }
					 }

				} else if (msg.what == LOAD_ERROR) {
					 Toast.makeText(context, "下载错误！", Toast.LENGTH_LONG).show();
					 if(appInfos!=null){
						 File file = new File(FileUtils.APK_DIR, appInfos.appName);
						 if(file.exists()){
							 file.delete();
						 }
					 }
					dismiss();

				}else if(msg.what==SHOWDOWNLOAD_DIALOG){
					 APKLoadPpopu.this.showAtLocation(localView, Gravity.CENTER, 0, 0);
				}
			};
		};

	/**
	 * 下载apk
	 */
		public void downFile() {
			new Thread() {
				public void run() {
					HttpResponse response= null;
					InputStream mInputStream = null;
					FileOutputStream fileOutputStream = null;
					try {
						HttpClient client = new DefaultHttpClient();
						HttpGet get = new HttpGet(appInfos.appDownloadUrl);
						response = client.execute(get);
						HttpEntity entity = response.getEntity();
						length = entity.getContentLength();
						File file = new File(FileUtils.APK_DIR, appInfos.appName);
						Log.w("APKLoadPpopu","download apkDir  :"+FileUtils.APK_DIR);
						boolean exist=checkFileExistInLocal(appInfos.appName);
						if(exist){
							if(file.length()==length){
							    FileUtils.installApk(context,appInfos.appName);
								return;
							}else{
								file.delete();
							}
						}
						handler.sendEmptyMessage(SHOWDOWNLOAD_DIALOG);
						mInputStream = entity.getContent();
						fileOutputStream = new FileOutputStream(file);
						byte[] buf = new byte[1024];
						int ch = -1;
						int count = 0;
						while ((ch = mInputStream.read(buf)) != -1) {
							fileOutputStream.write(buf, 0, ch);
							count += ch;
							Message message = handler.obtainMessage();
							message.what = UPDATE_PRO;
							message.arg1 = count;
							handler.sendMessage(message);
						}
						fileOutputStream.flush();
						Message message = handler.obtainMessage();
						message.what = UPDATE_COMPLETE;
						handler.sendMessage(message);
					} catch (Exception e) {
						Message message = handler.obtainMessage();
						message.what = LOAD_ERROR;
						handler.sendMessage(message);
						e.printStackTrace();
					}finally {
						try{
							if(mInputStream!=null){
								mInputStream.close();
								mInputStream=null;
							}
							if(fileOutputStream!=null){
								fileOutputStream.close();
								fileOutputStream=null;
							}
						}catch (Exception e){
							e.printStackTrace();
						}
					}
				}
			}.start();
		}

	private boolean checkFileExistInLocal(String fileName){
		File file = new File(FileUtils.APK_DIR);
		boolean isExist = false;
		if (file.exists()) {
			File[] files = file.listFiles();
			for (int i = 0; i < files.length; i++) {
				if (files[i].getName().equals(fileName)) {
					isExist = true;
					break;
				}
			}
		}
		return isExist;
	}

}
